package com.alone.openai.api.core;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;
import java.util.Objects;


/**
 * @author Alone
 * @date 2023/3/22 9:54 上午
 */
public class GlobalProperties {

    public static final String TOKEN_PREFIX = "Bearer ";
    private static final String YAML_FILE = "application.yml";
    private static final String OPEN_AI = "open-ai";
    private static final String API_KEY = "api-key";

    private static String token = null;
    static {
        String apiKey = getApiKey();
        checkApiKey(apiKey);
        token = TOKEN_PREFIX + apiKey;
    }

    public static String getToken() {
        return token;
    }

    private static String getApiKey() {
        Map<String, Object> data = new Yaml().load(Yaml.class.getClassLoader().getResourceAsStream(YAML_FILE));
        if (CollUtil.isNotEmpty(data)) {
            Map<String, Object> openAi = (Map<String, Object>) data.get(OPEN_AI);
            if (CollUtil.isNotEmpty(openAi)) {
                Object apiKey = openAi.get(API_KEY);
                if (Objects.nonNull(apiKey)) {
                    return apiKey.toString();
                }
            }
        }
        return null;
    }

    private static void checkApiKey(String apiKey) {
        if (StrUtil.isNotBlank(apiKey) && apiKey.startsWith("sk-") && apiKey.length() == 51) {
            return;
        }
        throw new IllegalArgumentException(
                String.format("your api_key: (%s) is illegal!",
                        StrUtil.isBlank(apiKey) ? "null" : apiKey)
        );
    }

}
